from celery import Celery
import xmlrpc.client
import sys
import os
import redis

from task_config import TASK_CONFIG

checksum_path=TASK_CONFIG['checksum']

app = Celery('tasks', backend=TASK_CONFIG['redis_server'], broker=TASK_CONFIG['redis_server'])
redis_client = redis.Redis(
    host=TASK_CONFIG['redis_host'], 
    port=TASK_CONFIG['redis_port'], 
    db=TASK_CONFIG['redis_db'],
    charset="utf-8", 
    decode_responses=True)
xmlrpc_host = redis_client.get('xmlrpc_host')
xmlrpc_port = redis_client.get('xmlrpc_port')
xmlrpc_server = 'http://{0}:{1}/'.format(xmlrpc_host, xmlrpc_port)
print('connected to %s' % (xmlrpc_server))
proxy = xmlrpc.client.ServerProxy(xmlrpc_server)

def UpateScriptFiles():
    latest_checksum = proxy.get_checksum()
    last_checksum = ''    
    if os.path.exists(checksum_path):
        with open(checksum_path, 'r') as fh:
            last_checksum = fh.read()
    if latest_checksum != last_checksum:
        try:
            with open(checksum_path, 'w') as fh:
                fh.write(latest_checksum)
            files = proxy.get_all_file_stream()
            count = 0
            for file in files:
                fp = 'fetched/' + file[0]
                fd = os.path.dirname(fp)
                fb = file[1]
                if not os.path.exists(fd):
                    os.makedirs(fd)
                with open(fp, 'wb') as fh:
                    count += 1
                    print('writing %s(%s)...' % (fp, count))
                    fh.write(fb.data)
            print("finished, fetched %s files." % (count))
        finally:
            pass
    else:
        print('no files changed.')

@app.task
def execute(args):
    script_dir=args['script_dir']
    script_name=args['script_name']
    UpateScriptFiles()
    sys.path.insert(0, './fetched/'+script_dir)
    module_name = script_name
    if module_name in sys.modules:
        del sys.modules[module_name]
    m = __import__(module_name)
    return m.execute(args)

